<template>
  <div class="UserIndexDialog">
    <el-dialog
      :close-on-click-modal="false"
      :title="dialog.classId ? '编辑商品类型' : '新增商品类型'"
      :visible="dialog.visible"
      width="630px"
      :before-close="closeFn"
    >
      <span>
        <el-form ref="newSkuForm" :model="newSkuForm" :rules="newSkuFormRules" label-width="140px">
          <el-form-item label="商品类型名称：" prop="className">
            <el-input v-model.trim="newSkuForm.className"
            placeholder="请输入"
            maxlength="5"
            show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFn" size="medium">取消</el-button>
        <!-- 新建人员确定 -->
        <el-button v-if="!dialog.classId" type="primary" size="medium" @click="postSKU">确定</el-button>
        <!-- 修改人员确定 -->
        <el-button v-if="dialog.classId" type="primary" size="medium" @click="putSKU">确定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出框结束 -->
  </div>
</template>

<script>
import {
  addSKU,
  putSKU
} from '@/api/skuAPIs'
export default {
  props: {
    dialog: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      // 表单信息
      newSkuForm: {
        className: ''
      },
      // 表單校驗
      newSkuFormRules: {
        className: [{ required: true, message: '商品类型名称' }]
      }
    }
  },
  methods: {
    async closeFn () {
      // 重置状态
      this.$emit('update:dialog', {
        visible: false,
        classId: 0,
        className: ''
      })
      // 重置表单状态
      this.newSkuForm = {
        className: ''
      }
      await this.$refs.newSkuForm.resetFields()
    },
    // 新增
    async postSKU () {
      try {
        await this.$refs.newSkuForm.validate()
        await addSKU(this.newSkuForm)
      } catch (e) {
        console.log(e)
      } finally {
        this.closeFn()
        this.$parent.getskuList(true)
      }
    },
    async putSKU () {
      try {
        await this.$refs.newSkuForm.validate()
        await putSKU({
          id: this.dialog.classId,
          data: this.newSkuForm
        })
        this.$parent.getskuList()
      } catch (e) {
        console.log(e)
      } finally {
        this.closeFn()
      }
    }
  },
  watch: {
    dialog: {
      handler (newVal) {
        console.log(newVal)
        if (newVal.classId) {
          this.newSkuForm = {
            className: newVal.className
          }
        }
      },
      deep: true // 深入監聽
    }
  }
}
</script>

<style lang="scss" scoped>
.UserIndexDialog {
  .el-form{
    padding-right: 40px;
  }
}
</style>
